﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MinerManager
{
    public partial class Utility
    {
		public class Forms
		{
			#region void FormClose(Form form) 关闭窗体。

			private delegate void DelegateFormClose(Form form);

			/// <summary>
			/// 关闭窗体。
			/// </summary>
			public static void FormClose(Form form)
			{
				if (form.InvokeRequired)
				{
					DelegateFormClose d = new DelegateFormClose(FormClose);
					form.BeginInvoke(d, form);
				}
				else
				{
					form.Close();
				}
			}

			#endregion

			#region void SetComboBoxEdit(Form form, string comboBoxName, List<ComboboxListItem> listItems, object selectedValue = null)

			private delegate void DelegeteSetComboBoxEdit(Form form, string comboBoxName, List<ComboboxListItem> listItems, object selectedValue = null);

			/// <summary>
			/// 为<see cref="ComboBoxEdit"/>控件赋值。
			/// </summary>
			/// <param name="form"></param>
			/// <param name="comboBoxName"></param>
			/// <param name="listItems"></param>
			/// <param name="selectedValue"></param>
			public static void SetComboBoxEdit(Form form, string comboBoxName, List<ComboboxListItem> listItems, object selectedValue = null)
			{
				if (form.InvokeRequired)
				{
					DelegeteSetComboBoxEdit d = new DelegeteSetComboBoxEdit(SetComboBoxEdit);
					form.BeginInvoke(d, form, comboBoxName, listItems, selectedValue);
				}
				else
				{
					Control[] controls = form.Controls.Find(comboBoxName, true);
					if (controls.Length > 0)
					{
						ComboBoxEdit control = (ComboBoxEdit)controls[0];
						control.Properties.Items.Clear();
						control.Properties.Items.AddRange(listItems);

						int selectedIndex = 0;
						if (selectedValue != null && !string.IsNullOrWhiteSpace(selectedValue.ToString()))
						{
							int index = listItems.FindIndex(p => p.Value == selectedValue.ToString());
							if (index >= 0)
								selectedIndex = index;
						}
						control.SelectedIndex = selectedIndex;
					}
				}
			}

			#endregion
		}
	}
}
